package edu.tjpu.share.task;

import java.util.HashMap;

import org.phprpc.PHPRPC_Client;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.biz.IUpdate;
import edu.tjpu.share.po.FileForDownload;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.service.DownloadService;

public class UpdateTask extends
		AsyncTask<HashMap<String, Object>, Integer, HashMap<String, Object>> {


	@Override
	protected HashMap<String, Object> doInBackground(
			HashMap<String, Object>... maps) {

		Handler updateHandler = (Handler) maps[0].get("updateHandler");
		Server serverinfo = (Server) maps[0].get(Fields.SERVER_INFO);
		int localVersion = (Integer) maps[0].get("localVersion");
		FileForDownload file;

		StringBuilder sbhost = new StringBuilder();
		sbhost.append("http://");
		sbhost.append(serverinfo.getHost());
		sbhost.append(":");
		sbhost.append(serverinfo.getProt());
		sbhost.append("/ShareServer/servlet/UpdateServlet");
		try {
			PHPRPC_Client updateClient = new PHPRPC_Client(sbhost.toString());
			IUpdate updateFile = (IUpdate) updateClient
					.useService(IUpdate.class);
			file = updateFile.doCheckUpdate(localVersion);
		} catch (Exception e) {
			updateHandler.sendEmptyMessage(DownloadService.DOWNLOAD_FAILED);
			return null;
		}

		HashMap<String, Object> outmap = new HashMap<String, Object>();
		outmap.put(Fields.HANDLER, updateHandler);
		outmap.put(Fields.FOR_DOWNLOAD, file);

		return outmap;
	}

	@Override
	protected void onPostExecute(HashMap<String, Object> result) {
		super.onPostExecute(result);
		if (isCancelled()) {
			result = null;
		}
		if (result != null) {
			FileForDownload file = (FileForDownload) result.get(Fields.FOR_DOWNLOAD);
			Handler updateHandler = (Handler) result.get(Fields.HANDLER);
			Message msg = updateHandler.obtainMessage();
			Bundle bundle = new Bundle();
			bundle.putSerializable("update", file);
			msg.setData(bundle);
			msg.what = DownloadService.DOWNLOAD_COMPLETE;
			updateHandler.sendMessage(msg);
		}
	}
}
